<template>
  <div>
    <v-toolbar flat color="white">
      <v-toolbar-title>My Files</v-toolbar-title>

      <v-divider class="mx-2" inset vertical></v-divider>
      <v-spacer>
        <v-btn @click="back()" color="primary" dark class="mb-2">返回上一层</v-btn>
        <v-btn @click="showAddFolder()" color="primary" dark class="mb-2">新建文件夹</v-btn>
      </v-spacer>
      <v-text-field v-model="search" append-icon="search" label="Search" single-line hide-details></v-text-field>
    </v-toolbar>
    <v-data-table
      hide-actions
      :headers="headers"
      :items="desserts"
      :search="search"
      class="elevation-1"
    >
      <template slot="items" slot-scope="props">
        <td v-if="props.item.isFile==0" class="blue text-xs-left">文件夹</td>
        <td v-else class="grey text-xs-left">文件</td>
        <td
          v-if="props.item.isFile==0"
          @click="isFile(props.item.isFile,props.item.filename,props.item.id)"
          class="text-xs-left"
        >{{ props.item.filename }}</td>
        <td v-else class="text-xs-left">{{ props.item.filename }}</td>

        <td style="display:none;" class="text-xs-left">{{ props.item.id }}</td>
        <td class="text-xs-left">{{ props.item.filePath }}</td>
        <td class="text-xs-left">{{ byteConvert(props.item.fileSize) }}</td>
        <td class="text-xs-left">{{ props.item.gmtCreated }}</td>

        <td v-if="props.item.isFile!=0" class="layout px-0">
          <v-icon
            small
            class="mr-2"
            @click="isFile(props.item.isFile,props.item.filename,props.item.id)"
          >mdi-download</v-icon>
          <v-icon small class="mr-2" @click="editItem(props.item)">mdi-pencil</v-icon>
          <v-icon small @click="shareThisFile(props.item.id)">mdi-link</v-icon>
          <v-icon small @click="deleteItem(props.item)">mdi-delete</v-icon>
        </td>
        <td v-else class="justify-center layout px-0">
          <v-icon small class="mr-2" @click="editItem(props.item)">mdi-folder-edit</v-icon>
        </td>
      </template>
      <template slot="no-data">
        <v-btn color="primary" @click="initialize">Reset</v-btn>
      </template>
    </v-data-table>
    <v-dialog v-model="dialog" max-width="500px">
      <v-card>
        <v-card-title>
          <span class="headline">{{ formTitle }}</span>
        </v-card-title>

        <v-card-text>
          <v-container grid-list-md>
            <v-layout wrap>
              <v-flex>
                <v-text-field v-model="editedItem.filename" label="Rename File"></v-text-field>
              </v-flex>
            </v-layout>
          </v-container>
        </v-card-text>

        <v-card-actions>
          <v-spacer></v-spacer>
          <v-btn color="blue darken-1" flat @click="close">Cancel</v-btn>
          <v-btn color="blue darken-1" flat @click="save">Save</v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>

    <v-dialog v-model="dialog2" max-width="500px">
      <v-card>
        <v-card-title>
          <span class="headline">{{ formTitle }}</span>
        </v-card-title>

        <v-card-text>
          <v-container grid-list-md>
            <v-layout wrap>
              <v-flex>
                <v-text-field v-model="newFolderName" label="新建文件夹"></v-text-field>
              </v-flex>
            </v-layout>
          </v-container>
        </v-card-text>

        <v-card-actions>
          <v-spacer></v-spacer>
          <v-btn color="blue darken-1" flat @click="close">Cancel</v-btn>
          <v-btn color="blue darken-1" flat @click="savefolder()">完成</v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>
  </div>
</template>
<script>
export default {
  name: "container",
  data: () => ({
    dialog: false,
    dialog2: false,
    headers: [
      { text: "isFile", value: "isFile" },
      {
        text: "File Name",
        align: "left",
        sortable: true,
        value: "filename"
      },
      //{ text: 'isFile', value: 'isFile' },
      { text: "File Path", value: "filePath" },
      { text: "File Size", value: "fileSize" },
      { text: "Upload Date", value: "gmtCreated" },

      { text: "Actions", value: "name", sortable: false }
    ],
    desserts: [],
    editedIndex: -1,
    editedItem: {
      filename: ""
    },
    defaultItem: {
      filename: ""
    },
    search: "",
    username: "",
    lastPath: "",
    currentPath: "",
    newFolderName: ""
  }),

  computed: {
    formTitle() {
      return this.editedIndex === -1 ? "New Item" : "Edit Item";
    }
  },

  watch: {
    dialog(val) {
      val || this.close();
    }
  },

  created() {
    this.username = sessionStorage.getItem("username");
    this.currentPath = "/" + this.username + "/";
    //alert(this.currentPath);
    this.initialize(this.currentPath);
  },

  methods: {
    initialize() {
      // this.lastPath=this.currentPath;
      // this.currentPath=path;
      let formData = new FormData();
      formData.append("path", this.currentPath);

      this.$http
        .post(
          "file/fileList/" +
            sessionStorage.getItem("username") +
            "?access_token=" +
            sessionStorage.getItem("token"),
          formData
        )
        .then(response => {
          this.desserts = response.data;

          //console.log(response.data);
        });
    },

    editItem(item) {
      this.editedIndex = this.desserts.indexOf(item);
      this.editedItem = Object.assign({}, item);
      this.dialog = true;
      

    },

    deleteItem(item) {
      const index = this.desserts.indexOf(item);
      confirm("Are you sure you want to delete this item?") &&
        this.desserts.splice(index, 1);
    },

    close() {
      this.dialog = false;
      setTimeout(() => {
        this.editedItem = Object.assign({}, this.defaultItem);
        this.editedIndex = -1;
      }, 300);
    },

    save() {
      if (this.editedIndex > -1) {
        Object.assign(this.desserts[this.editedIndex], this.editedItem);
      } else {
        this.desserts.push(this.editedItem);
      }
      this.close();
    
     let fd=new FormData();
     fd.append("newFileName",this.editedItem.filename);
     fd.append("originFileId",this.editedItem.id);
     this.$http.post("/file/renameFile/"+this.username,fd).then(res=>{
       alert(res.data);
     });

    },

    isFile(e, p, i) {
      if (e == 0) {
        // alert(p);
        this.lastPath = this.currentPath;
        this.currentPath += p + "/";
        //alert(this.currentPath);
        this.initialize(this.currentPath);
      } else {
        alert("It's a file,ID is: " + i);
        let formData = new FormData();

        formData.append("originFileId", i);

        window.location = encodeURI(
          "file/download/" +
            sessionStorage.getItem("username") +
            "?access_token=" +
            sessionStorage.getItem("token") +
            "&originFileId=" +
            i
        );
      }
    },
    back() {
      if (!(this.currentPath == "/" + this.username + "/")) {
        var t = this.currentPath;
        var arr = t.split("/");
        arr.pop();
        arr.pop();
        t = arr.join("/") + "/";
        this.currentPath = t;
        //alert("this.lastPath" + t);
        this.initialize();
      }
    },
    showAddFolder() {
      this.dialog2 = true;
    },
    savefolder() {
      this.dialog2 = false;
      alert(this.newFolderName);
      let formData = new FormData();

      formData.append("folderName", this.newFolderName);
      formData.append("path", this.currentPath);
      this.$http
        .post(
          "/file/addFolder/" +
            this.username +
            "?access_token=" +
            sessionStorage.getItem("token"),
          formData
        )
        .then(res => {
          alert(res.data);
        });
    },
    shareThisFile(fId) {
      //alert(fId);
      let formData = new FormData();

      formData.append("needCode", 1);
      formData.append("originFileId", fId);

      this.$http
        .post("/share/setShareFile/" + this.username, formData)
        .then(res => {
          if (res.data != "fail") {
            var str = "http://localhost:8080/#/share/" + res.data.shareKey;

            alert("分享链接：" + str + "提取码：" + res.data.extractCode);
          }
        });
    }
    ,
    byteConvert: function(bytes) {
      if (isNaN(bytes)) {
        return "";
      }
      var symbols = ["bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"];
      var exp = Math.floor(Math.log(bytes) / Math.log(2));
      if (exp < 1) {
        exp = 0;
      }
      var i = Math.floor(exp / 10);
      bytes = bytes / Math.pow(2, 10 * i);

      if (bytes.toString().length > bytes.toFixed(2).toString().length) {
        bytes = bytes.toFixed(2);
      }
      return bytes + " " + symbols[i];
    }
  }
};
</script>
